import { defineStore } from "pinia"
import { ref } from "vue"
import { GETTOKEN, REMOVETOKEN, SETTOKEN } from "@/utils/local"
import { userLogin, getUserInfoApi } from "@/api/user"
interface loginParams {
    username: string
    password: string
    captcha: string
}
export const useUserStore = defineStore(
    "user",
    () => {
        /***
         * @登录
         */
        const token = ref("" || GETTOKEN())
        const userinfo = ref(<any>{})
        // 用户登录
        const loginUp = async (loginParams: loginParams) => {
            const res: any = await userLogin(loginParams)
            if (res.code === 200) {
                token.value = res.data.token
                SETTOKEN(res.data.token)
                await getUserInfo()
                return "登录成功"
            } else {
                return Promise.reject(new Error(res.message))
            }
        }
        // 获取用户信息
        const getUserInfo = async () => {
            const res = await getUserInfoApi()
            if (res.code === 200) {
                userinfo.value = res.data.user
                // const permissionStore = usePermissionStore()
                // permissionStore.setPermissions(res.data.permissions)
            } else {
                return Promise.reject(new Error(res.message))
            }
        }
        // 退出登录
        const loginOut = () => {
            REMOVETOKEN()
            userinfo.value = {}
        }
        return {
            token,
            userinfo,
            loginUp,
            loginOut,
        }
    },

)
